package com.gr.jron.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.gr.jron.service.GenericManager;
import com.gr.jron.model.Jimage;
import com.gr.jron.webapp.action.BaseAction;

import java.util.List;

public class JimageAction extends BaseAction implements Preparable {
    private GenericManager<Jimage, Long> jimageManager;
    private List jimages;
    private Jimage jimage;
    private Long  id;

    public void setJimageManager(GenericManager<Jimage, Long> jimageManager) {
        this.jimageManager = jimageManager;
    }

    public List getJimages() {
        return jimages;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String jimageId = getRequest().getParameter("jimage.id");
            if (jimageId != null && !jimageId.equals("")) {
                jimage = jimageManager.get(new Long(jimageId));
            }
        }
    }

    public String list() {
        jimages = jimageManager.getAll();
        return SUCCESS;
    }

    public void setId(Long  id) {
        this. id =  id;
    }

    public Jimage getJimage() {
        return jimage;
    }

    public void setJimage(Jimage jimage) {
        this.jimage = jimage;
    }

    public String delete() {
        jimageManager.remove(jimage.getId());
        saveMessage(getText("jimage.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            jimage = jimageManager.get(id);
        } else {
            jimage = new Jimage();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (jimage.getId() == null);

        jimageManager.save(jimage);

        String key = (isNew) ? "jimage.added" : "jimage.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}